<template>
  <div
    :class="isFull ? 'mpr-box-fulled' : 'mpr-box-normal'"
    @mousemove="onMousemove($event)"
    @mouseup="onMouseup"
    @mousedown="onMousedown"
    @dblclick="toggleImageSize"
  >
    <div :id="boxIdx === 0 ? 'axial' : (boxIdx === 1 ? 'sagittal' : 'coronal')" class="canvas-content" ref="box" oncontextmenu="return false"></div>
    <i :class="['iconfont', isFull ? 'icon-xiaoping' : 'icon-a-quanping1']" @click="toggleImageSize"></i>
    <corner-info :corner-info="{ ...cornerInfo1, total }" v-if="isCornerInfo"></corner-info>
    <cross :styles="styles" :colors="colors" ref="crossHair" v-if="isCrosshairVisible"></cross>
  </div>
</template>

<script lang="ts">
  // @ts-nocheck
  import { default as _get } from 'lodash/get'
  import throttle from "lodash/throttle"
  import _ from 'lodash';
  import * as cornerstone from "cornerstone-core"
  import cornerstoneTools from "cornerstone-tools"
  import Cross from './cross.vue'
  import CornerInfo from './corner-info.vue'
  import SyncBrushTool from "./SyncBrushTool"
  import { getImagePointArray } from "./SyncBrushTool/utils/pointArray"
  import { MRPINFO, synchronizer, wwwcSynchronizer } from "./config"
  import referencePoint from "./referencePoint"
  import MprCrossTool from "./MprCrossTool"
  
  // import RectangleTool from "@/utils/RectangleTool";
  // import {saveMaskAnnoData} from "@/api/readPathology/readPathology";
  // import {Message} from "@arco-design/web-vue";
  import { ElMessage } from "element-plus";
  import { saveAnnoData, updateAnnoData } from '@/api/readPathology/readPathology';
  import { Rectangle_colormap } from "@/utils/colorMap"
  import useUtils from "@/views/filmRead/hooks/useUtils";
  
  const { configuration, getters, setters, state } = cornerstoneTools.getModule("segmentation") // cornerstoneTools.store.modules.segmentation
  const { getToolState } = cornerstoneTools

  const { imagePointToPatientPoint, projectPatientPointToImagePlane, planePlaneIntersection } = referencePoint()

  const scrollToIndex = cornerstoneTools.importInternal('util/scrollToIndex')

  export default {
    components: {
      Cross,
      CornerInfo,
    },
    props: {
      boxIdx: {
        type: [String, Number]
      },
      isCrosshairVisible: {
        type: Boolean,
        default: false
      },
      cornerInfo: {
        type: Object,
        default: () => {}
      }
    },
    inject: ['mprViewer','xyz'],
    data() {
      return {
        enabled: false, //是否挂完片
        currentIm: 0,
        currentWl: undefined,
        currentWw: undefined,
        sliceThickness: undefined, // 层厚
        kvp: undefined, // kvp
        xRayTubeCurrent: undefined, // X-Ray Tube Current
        styles: { top: '-2px', left: '-2px' },
        colors: { leftColor: '#79b904', topColor: '#79b904' },
        isFull: false, // 是否全屏展示
        total: 0,
        isCornerInfo: true
      }
    },
    // watch: {
    //   nidusMasks: {
    //     handler(val) {
    //       val&& this.drawAxialMask()
    //     },
    //     immediate: true
    //   }
    // },
    computed: {
      cornerInfo1() {
        return {
          ...this.cornerInfo,
          currentIm: this.currentIm,
          wl: this.currentWl,
          ww:  this.currentWw
        }
      }
    },
    created() {},
    mounted() {
      this.element = this.$refs.box
      // cornerstoneTools.setToolActive('ScaleOverlay')
      // cornerstoneTools.setToolActiveForElement(this.element, 'ScaleOverlay') // 只对当前的element设置有效，不影响全局的设置
    },
    methods: {
      toggleImageSize() {
        this.isFull = !this.isFull;
        this.mprViewer.boxFull(this.boxIdx, this.isFull)
        this.$nextTick(() => {
          if (!this.enabled) return false
          cornerstone.resize(this.element)
        })
      },
      scrollToIndex(layer) {
        scrollToIndex(this.element, layer)
      },
      getMprPosPercent(dividend, divisor) {
        return `${100*(dividend/divisor)}%`
      },
      reset() {
        cornerstone.reset(this.element)
      },
      setWL(wl, ww) {
        const viewport = cornerstone.getViewport(this.element)
        if (!viewport) return
        viewport.voi.windowCenter = wl * 1
        viewport.voi.windowWidth = ww * 1
        cornerstone.setViewport(this.element, viewport)
      },
      onMousemove(evt) {
        if (evt instanceof MouseEvent) {
          this.coords = evt.target
          this.coordsElement = this.element
        } else {
          const eventData = evt.detail
          const { element } = eventData
          this.coords = eventData.currentPoints.canvas
          this.coordsElement = element
        }
      },
      onMouseup(){},
      onMousedown(){},
      getImageOrientationPatient(dicom) {
        const { data: { elements, byteArray }} = dicom;
        const { length, dataOffset } = (elements.x00200037 || {});
        if (!length) return ''
        return (new TextDecoder().decode(new Uint8Array(byteArray.buffer, dataOffset, length))).replace(/\\/g, ',')
      },
      // 计算方向标
      calculateOrientationMarkers(imageOrientationPatient) {
        if (imageOrientationPatient == null) {
          this.markers = {
            top: '',
            bottom: '',
            left: '',
            right: ''
          }
          return
        }
        const oriArr = imageOrientationPatient.split(',')
        const rowCosines = oriArr.slice(0, 3)
        const columnCosines = oriArr.slice(3, 6)
        const rowString = cornerstoneTools.orientation.getOrientationString(rowCosines)
        const columnString = cornerstoneTools.orientation.getOrientationString(columnCosines)
        const oppositeRowString = cornerstoneTools.orientation.invertOrientationString(rowString)
        const oppositeColumnString = cornerstoneTools.orientation.invertOrientationString(columnString)
        this.markers = {
          top: oppositeColumnString,
          bottom: columnString,
          left: oppositeRowString,
          right: rowString
        }
      },
      onKeyDown(evt) {
        evt.preventDefault()
        if (evt.keyCode === 46) {
          this.onContextMenu()
        }
        return false
      },
      isEnable(element) {
        return cornerstone.getEnabledElements().map((item) => { return item.element }).includes(element)
      },
      onContextMenu() {
        const { state } = cornerstoneTools.store;
        const { coordsElement: element, coords } = this
        try {
          state.tools.forEach((tool) => {
            const toolState = this.isEnable(element) && getToolState(element, tool.name);
            if (toolState) {
              // Modifying in a foreach? Probably not ideal
              toolState.data.forEach((data)=> {
                if (
                  typeof tool.pointNearTool === 'function' &&
                  tool.pointNearTool(element, data, coords)
                ) {
                  cornerstoneTools.removeToolState(element, tool.name, data);
                  ElMessage.success('删除成功');
                  cornerstone.updateImage(element);
                }
              });
            }
          });
        } catch (error) {

        }
        return false //禁用canvas右键
      },
      async hangIds(imageIds, tag) {
        const { element } = this
        this.total = imageIds.length
        this.imageIds = imageIds
        const _this = this
        MRPINFO.setVal('MPRISWHEEL', false)
        if(imageIds[0].includes('wadouri')){//dicomweb
          this.colors = {leftColor:'#f8e71c',topColor:'#e26a6a'}
          this.styles = {left:'50%', top:'50%'}
        }
        if(imageIds[0].includes('sagittal')){
          this.colors = {leftColor:'#e26a6a',topColor:'#1cd11c'}
          this.styles = {left:'50%', top:'50%'}
        }
        if(imageIds[0].includes('coronal')){
          this.colors = {leftColor:'#f8e71c',topColor:'#1cd11c'}
          this.styles = {left:'50%', top:'50%'}
        }
        this.enabled = true;
        cornerstone.disable(element);
        cornerstone.enable(element)
        const mid = Math.floor(imageIds.length / 2)
        const image = await cornerstone.loadAndCacheImage(imageIds[mid])
        cornerstone.displayImage(element, image)
        synchronizer.add(element)
        wwwcSynchronizer.add(element)

        this.max = imageIds.length
        if (tag === 2) {
          this.calculateOrientationMarkers(this.getImageOrientationPatient(image))
        }
        this.$options.throttleHandle = throttle((evt) => {
          MRPINFO.setVal('MPRISWHEEL', false)
          evt.preventDefault()
          const {image:{imageId}, currentPoints:{canvas,image}} = evt.detail;
          const { axialBoxRef: m_, sagittalBoxRef: s_, coronalBoxRef: c_ } = this.mprViewer.$refs // 轴cell组件/冠状cell组件/矢状cell组件
          const _styles = { top: _this.getMprPosPercent(canvas.y, evt.target.clientHeight), left: _this.getMprPosPercent(canvas.x, evt.target.clientWidth) }
          if (imageId.includes('wadouri')) {// dicomweb
            // const curr = imageIds.indexOf(imageId);
            // const len = curr?((curr*((s_.$el.clientHeight)/(imageIds.length)))+((s_.$el.clientHeight)/(imageIds.length))/2):0;
            const c_p_t_i = projectPatientPointToImagePlane(imagePointToPatientPoint(image,m_._imagePlane),c_._imagePlane);
            const s_p_t_i = projectPatientPointToImagePlane(imagePointToPatientPoint(image,m_._imagePlane),s_._imagePlane);
            const c_x_y=  cornerstone.pixelToCanvas(c_.element,c_p_t_i)
            const s_x_y=  cornerstone.pixelToCanvas(s_.element,s_p_t_i)
            /*if (curr == 0) {
              this.firstY = c_x_y.y;
            }*/
            m_.styles = _styles
            c_.styles = { top: _this.getMprPosPercent(c_x_y.y,c_.$el.clientHeight), left: _this.getMprPosPercent(c_x_y.x,c_.$el.clientWidth)}
            s_.styles = { top: _this.getMprPosPercent(s_x_y.y,s_.$el.clientHeight), left: _this.getMprPosPercent(s_x_y.x,s_.$el.clientWidth)}
          }
          if (imageId.includes('sagittal')) {
            const m_p_t_i = projectPatientPointToImagePlane(imagePointToPatientPoint(image,s_._imagePlane),m_._imagePlane);
            // const c_p_t_i = projectPatientPointToImagePlane(imagePointToPatientPoint(image,s_._imagePlane),c_._imagePlane);
            const m_x_y=  cornerstone.pixelToCanvas(m_.element,m_p_t_i)
            // const c_x_y=  cornerstone.pixelToCanvas(c_.element,c_p_t_i)
            s_.styles = _styles
            m_.styles = { top: _this.getMprPosPercent(m_x_y.y,m_.$el.clientHeight), left: m_.styles.left}
            c_.styles = { top: _this.getMprPosPercent(canvas.y,c_.$el.clientHeight), left: c_.styles.left}
          }
          if (imageId.includes('coronal')) {
            const m_p_t_i = projectPatientPointToImagePlane(imagePointToPatientPoint(image,c_._imagePlane),m_._imagePlane);
            const s_p_t_i = projectPatientPointToImagePlane(imagePointToPatientPoint(image,c_._imagePlane),s_._imagePlane);
            const m_x_y=  cornerstone.pixelToCanvas(m_.element,m_p_t_i)
            const s_x_y=  cornerstone.pixelToCanvas(s_.element,s_p_t_i)
            c_.styles = _styles
            m_.styles = { top: _this.getMprPosPercent(m_x_y.y,m_.$el.clientHeight), left: _this.getMprPosPercent(m_x_y.x,m_.$el.clientWidth)}
            s_.styles = { top: _this.getMprPosPercent(canvas.y,s_.$el.clientHeight), left: _this.getMprPosPercent(s_x_y.x,s_.$el.clientWidth)}
          }
        }, 100)
        cornerstoneTools.addStackStateManager(element, [
          "stack",
          "Crosshairs"
        ])
        /*cornerstoneTools.addToolForElement(
          element,
          cornerstoneTools.ReferenceLinesTool,
        )*/
        cornerstoneTools.addToolState(element, "stack", {
          imageIds: [...imageIds],
          currentImageIdIndex: mid,
        })
        cornerstoneTools.addToolForElement(
          element,
          MprCrossTool,
          {
            evtCallBack(evt) {
              _this.$options.throttleHandle(evt)
            }
          },
        )
        //定制框
        /*cornerstoneTools.addTool(RectangleTool,{
          configuration: {
            fillStyle: 'rgba(255,0,0,0.3)'
          }
        })*/
        /*cornerstoneTools.addToolForElement(
          element,
          cornerstoneTools.StackScrollMouseWheelTool,
        )*/
        cornerstoneTools.addToolForElement(element, SyncBrushTool)
        /*cornerstoneTools.addToolForElement(
          element,
          cornerstoneTools.CorrectionScissorsTool
        )*/
        cornerstoneTools.setToolActive("StackScrollMouseWheel", {
          mouseButtonMask: 0,
        })

        /*cornerstoneTools.setToolActive("Crosshairs", {
          mouseButtonMask: 2,
          synchronizationContext: synchronizer,
        })*/

        cornerstoneTools.setToolActiveForElement(element, "Wwwc", {
          mouseButtonMask: 1 // 左键
        })
        cornerstoneTools.setToolActiveForElement(element, "StackScroll", {
          mouseButtonMask: 4 // 中键(快速翻页)
        })
        cornerstoneTools.setToolActiveForElement(element, "Pan", {
          mouseButtonMask: 2 // 右键
        })

        element.removeEventListener('keydown', _this.onKeyDown)
        element.removeEventListener('cornerstonetoolsmousemove', _this.onMouseMove)
        element.removeEventListener('cornerstonetoolsmousewheel', wheelImage)
        element.removeEventListener('cornerstoneimagerendered', renderImage)
        element.removeEventListener('cornerstonenewimage', onNewImage)
        element.addEventListener('cornerstonetoolsmousewheel', wheelImage)
        element.addEventListener('cornerstoneimagerendered', renderImage)
        element.addEventListener('cornerstonenewimage', onNewImage)
        element.addEventListener('cornerstonetoolsmousemove', _this.onMouseMove)
        element.addEventListener('keydown', _this.onKeyDown)
        element.addEventListener('cornerstonetool', _this.onKeyDown)
        element.addEventListener(cornerstoneTools.EVENTS.MEASUREMENT_ADDED, _this.measurementAdded.bind(_this));
        element.addEventListener(cornerstoneTools.EVENTS.MEASUREMENT_MODIFIED, _.debounce(_this.measurementModified, 300));
        element.addEventListener(cornerstoneTools.EVENTS.MEASUREMENT_COMPLETED, _this.measurementCompleted);
        element.addEventListener(cornerstoneTools.EVENTS.MEASUREMENT_REMOVED, _this.measurementRemoved);
        element.oncontextmenu = _this.onContextMenu
        function wheelImage(evt) {
          MRPINFO.setVal('MPRISWHEEL', true)
        }
        function renderImage(evt) {
          const viewport = cornerstone.getViewport(_this.element)
          const imageId = evt.detail.image.imageId
          _this.currentIm = _this.imageIds.indexOf(imageId)
          const { windowCenter, windowWidth } = viewport.voi;
          [_this.currentWl, _this.currentWw] = [parseInt(windowCenter), parseInt(windowWidth)];
          _this._imagePlane = cornerstone.metaData.get(
            'imagePlaneModule',
            imageId
          )
          _this.zomm = viewport.scale
          //更新十字线
          // if(MRPINFO.getVal('MPRISWHEEL')) {//换层
            _this.mprViewer.mprBoxs.map(target => {
              if(target.element !== _this.element){
                _this.updateReferLine(target, _this)
              }
            })
          // }else{//缩放、移动
            //更新自己十字线
            _this.mprViewer.mprBoxs.map(target => {
              if(target.element !== _this.element){
                _this.updateReferLine(_this, target)
              }
            })
          // }
          // 判断是否是轴切面滚动
          /*if (imageId.includes('wadouri') && MRPINFO.getVal('MPRISWHEEL')) {//dicomweb
            _this.drawReferImageLine(evt)
          }*/
        }
        function onNewImage(evt) {
          const imageId = evt.detail.image.imageId
          // _this.currentIm = _this.imageIds.indexOf(imageId)
          if (_this.boxIdx === 0) {
            const parentRef = _this.mprViewer
            /*SyncBrushTool.endLayer = parentRef.crossLayer > 1 ? _this.currentIm + parentRef.crossLayer - 1 : _this.currentIm
            if (configuration.customParams) {
              configuration.customParams.layerStart = _this.currentIm
              configuration.customParams.layerEnd = SyncBrushTool.endLayer
            }*/
            // _this.drawAxialMask()
          } else {
            // _this.drawSagittalCoronalMask()
          }
          /*const {
            labelmap3D,
            activeLabelmapIndex,
            currentImageIdIndex,
          } = getters.labelmap2D(_this.element)
          console.log('newimage', labelmap3D,activeLabelmapIndex,currentImageIdIndex)
          console.log('brushstate', state, configuration)*/
          // console.log(cornerstoneTools.getToolState(_this.element, 'Rectangle'))
        }
      },
      measurementAdded(evt){
        // console.log('measurementAdded', evt)
        const { measurementData, toolName } = evt.detail;
        if(toolName === 'Rectangle'){

        }
      },
      measurementModified(evt) {
        // console.log('measurementModified', evt)
        const { lesionEvent, seriesEvent } = useUtils();
        const {measurementData: {uuid ,handles:{start,end}}, toolName, element} = evt.detail;
        const {allLesionResult, axialBox, sagittalBox, coronalBox, mprBoxs, axialImageIds, sagittalImageIds, coronalImageIds, pivotImagePoint,addOneCuboid, selectOneCuboid, scrollToMid} = this.mprViewer
        //todo
        // return
        if(toolName === 'Rectangle'){
          //得到当前3d坐标
          const selectCuboid = allLesionResult.find(({ id }) => id === uuid)
          if(!selectCuboid) return
          const baseImageId = axialImageIds[0]
          const {rows, columns} = cornerstone.metaData.get(
              "imagePlaneModule",
              baseImageId,
          )
          const {data: {point1, point2}} = (typeof selectCuboid.result === 'string')? JSON.parse(selectCuboid.result): selectCuboid.result
          //根据修改后的计算三个方向的坐标
          let param = {alrId: uuid, result: {}, color: ''}
          const color = 'rgba(0,206,209,1)';
          if(this.boxIdx === 0){
            //更新3d坐标
            let p1 = { x: start.x, y: start.y },p2 = { x: end.x, y: end.y }
            p1.z = point1.z
            p2.z = point2.z
            //todo 校验边界
            p1 = this.validatePoint('axial', p1)
            p2 = this.validatePoint('axial', p2)
            param.result = JSON.stringify({data: {point1: p1, point2: p2}, version: 1})
            //通过uuid更新所有rectangle
            //axial
            this.updateOneCuboid(axialImageIds,uuid, p1, p2)
            //sagittal
            const p1_sagittal = pivotImagePoint(p1, columns,'axial','sagittal')
            const p2_sagittal = pivotImagePoint(p2, columns,'axial','sagittal')
            //先删除再添加
            // this.updateOneCuboid(sagittalImageIds,uuid, p1_sagittal, p2_sagittal)
            this.removeCuboid(sagittalImageIds, uuid, toolName)
            addOneCuboid(uuid, color, sagittalImageIds, p1_sagittal, p2_sagittal)
            //coronal
            const p1_coronal = pivotImagePoint(p1, columns,'axial','coronal')
            const p2_coronal = pivotImagePoint(p2, columns,'axial','coronal')
            // this.updateOneCuboid(coronalImageIds,uuid, p1_coronal, p2_coronal)
            this.removeCuboid(coronalImageIds, uuid, toolName)
            addOneCuboid(uuid, color, coronalImageIds, p1_coronal, p2_coronal)
          }else if(this.boxIdx === 1){
            //存的3d坐标转成sagittal，然后替换x,y得到新的sagittal的3d坐标，然后转axial和coronal
            const p1_sagittal = pivotImagePoint(point1, columns,'axial','sagittal')
            const p2_sagittal = pivotImagePoint(point2, columns,'axial','sagittal')
            console.log('更新前sagittal 3d:',p1_sagittal,p2_sagittal)
            //update
            let p1 = { x: start.x, y: start.y },p2 = { x: end.x, y: end.y }
            p1.z = p1_sagittal.z
            p2.z = p2_sagittal.z
            p1 = this.validatePoint('sagittal', p1)
            p2 = this.validatePoint('sagittal', p2)
            console.log('更新后sagittal 3d:',p1,p2)
            //sagittal
            this.updateOneCuboid(sagittalImageIds,uuid, p1, p2)
            //axial
            const p1_axial = pivotImagePoint(p1, columns,'sagittal','axial')
            const p2_axial = pivotImagePoint(p2, columns,'sagittal','axial')
            // this.updateOneCuboid(axialImageIds,uuid, p1_axial, p2_axial)
            this.removeCuboid(axialImageIds, uuid, toolName)
            addOneCuboid(uuid, color, axialImageIds, p1_axial, p2_axial)
            console.log('转换为axial 3d:',p1_axial,p2_axial)
            param.result = JSON.stringify({data: {point1: p1_axial, point2: p2_axial}, version: 1})
            //coronal
            const p1_coronal = pivotImagePoint(p1, columns,'sagittal','coronal')
            const p2_coronal = pivotImagePoint(p2, columns,'sagittal','coronal')
            // this.updateOneCuboid(coronalImageIds,uuid, p1_coronal, p2_coronal)
            this.removeCuboid(coronalImageIds, uuid, toolName)
            addOneCuboid(uuid, color, coronalImageIds, p1_coronal, p2_coronal)
          }else if(this.boxIdx === 2){
            //存的3d坐标转成coronal，然后替换x,y得到新的coronal的3d坐标，然后转axial和coronal
            const p1_coronal = pivotImagePoint(point1, columns,'axial','coronal')
            const p2_coronal = pivotImagePoint(point2, columns,'axial','coronal')
            //update
            let p1 = { x: start.x, y: start.y },p2 = { x: end.x, y: end.y }
            p1.z = p1_coronal.z
            p2.z = p2_coronal.z
            p1 = this.validatePoint('coronal', p1)
            p2 = this.validatePoint('coronal', p2)
            //coronal
            this.updateOneCuboid(coronalImageIds,uuid, p1, p2)
            //axial
            const p1_axial = pivotImagePoint(p1, columns,'coronal','axial')
            const p2_axial = pivotImagePoint(p2, columns,'coronal','axial')
            // this.updateOneCuboid(axialImageIds,uuid, p1_axial, p2_axial)
            this.removeCuboid(axialImageIds, uuid, toolName)
            addOneCuboid(uuid, color, axialImageIds, p1_axial, p2_axial)
            param.result = JSON.stringify({data: {point1: p1_axial, point2: p2_axial}, version: 1})
            //sagittal
            const p1_sagittal = pivotImagePoint(p1, columns,'coronal','sagittal')
            const p2_sagittal = pivotImagePoint(p2, columns,'coronal','sagittal')
            // this.updateOneCuboid(sagittalImageIds,uuid, p1_sagittal, p2_sagittal)
            this.removeCuboid(sagittalImageIds, uuid, toolName)
            addOneCuboid(uuid, color, sagittalImageIds, p1_sagittal, p2_sagittal)
          }
          //todo 选中
          selectOneCuboid(uuid, true, 'Rectangle');
          cornerstoneTools.setToolActive('Rectangle', {mouseButtonMask: 1}); //可连续新增
          lesionEvent.lesionSetActive(uuid, true)
          //api
          updateAnnoData(param).then(res => {
            //todo 参数
            const result = JSON.parse(param.result)
            lesionEvent.lesionUpdate(uuid, {result})
            scrollToMid(result.data.point1, result.data.point2)
            console.log('编辑长方体结果', res)
            ElMessage.success('编辑病灶成功')
          })
        }
      },
      //del one direct some id
      removeCuboid(imageIds, uuid, toolName) {
        const { toolState } = cornerstoneTools.globalImageIdSpecificToolStateManager;
        for (const imageId of imageIds) {
          if(!toolState[imageId]) continue
          if(!toolState[imageId][toolName]) continue
          let { data } = toolState[imageId][toolName];
          for (let i = data.length - 1; i >= 0; i--) {
            if (data[i].uuid === uuid) {
              data.splice(i, 1);
            }
          }
        }
      },
      //更新一个方向的某个长方体 notice: 仅更新x,y,不适用更新z=imageId
      updateOneCuboid(imageIds, uuid, p1, p2){
        const { getImageIdToolState } = cornerstoneTools.globalImageIdSpecificToolStateManager
        for(const imageId of imageIds){
          const rectangleArr = getImageIdToolState(imageId, "Rectangle")
          if(!rectangleArr) continue
          const { data } = rectangleArr
          data.forEach(it => {
            if(it.uuid === uuid){
              it.handles.start.x = p1.x
              it.handles.start.y = p1.y
              it.handles.end.x = p2.x
              it.handles.end.y = p2.y
            }
          })
        }
      },
      measurementCompleted(evt){
        console.log('measurementCompleted', evt)
        const { lesionEvent, seriesEvent } = useUtils();
        const {measurementData: {handles:{start,end}}, toolName, element} = evt.detail;
        const { scrollToMid,pivotImagePoint,addOneCuboid,selectOneCuboid, mprBoxs,axialImageIds, sagittalImageIds, coronalImageIds } = this.mprViewer
        if(toolName === 'Rectangle'){//目前只在axial面创建
          //计算三维坐标调用接口
          let p1 = { x: start.x, y: start.y },p2 = { x: end.x, y: end.y }
          const distance = Math.max(Math.abs(start.x - end.x), Math.abs(start.y - end.y))
          const z1 = this.currentIm
          const z2 = Math.min(z1 + distance, this.total)
          p1.z = z1
          p2.z = z2
          p1 = this.validatePoint('axial', p1)
          p2 = this.validatePoint('axial', p2)
          const result = {data: {point1: p1, point2: p2}, version: 1}
          this.mprViewer.cuboidParam.result = JSON.stringify(result)
          // return;
          //超出问题
          saveAnnoData(this.mprViewer.cuboidParam).then(res => {
            const alrId = res.alrId || res.data.alrId
            ElMessage.success('创建病灶成功')
            lesionEvent.lesionAdd({id: alrId,...this.mprViewer.cuboidParam,imageCompList: this.mprViewer.imageCompList,result})
            //十字线定位
            scrollToMid(p1, p2)
            //alrId 注入store
            //删除画的
            const rectangleData = cornerstoneTools.getToolState(element, "Rectangle")
            const rectangleArr = rectangleData && rectangleData.data || []
            for (let i = rectangleArr.length - 1; i >= 0; i--) {
              if (rectangleArr[i].uuid === 'new') {
                rectangleArr.splice(i, 1);
              }
            }
            //计算三个面的平面坐标添加矩形框
            const baseImageId = axialImageIds[0]
            const {rows, columns} = cornerstone.metaData.get(
                "imagePlaneModule",
                baseImageId,
            )
            //axialBox
            addOneCuboid(alrId, Rectangle_colormap[7], axialImageIds, p1, p2)
            //sagittalBox
            const p1_3d_sagittal = pivotImagePoint(p1, columns,'axial','sagittal')
            const p2_3d_sagittal = pivotImagePoint(p2, columns,'axial','sagittal')
            addOneCuboid(alrId, Rectangle_colormap[7], sagittalImageIds, p1_3d_sagittal, p2_3d_sagittal)
            //coronalBox
            const p1_3d_coronal = pivotImagePoint(p1, columns,'axial','coronal')
            const p2_3d_coronal = pivotImagePoint(p2, columns,'axial','coronal')
            addOneCuboid(alrId, Rectangle_colormap[7], coronalImageIds, p1_3d_coronal, p2_3d_coronal)
            selectOneCuboid(alrId, true,'Rectangle')
            mprBoxs.map(it => it.updateImage())
            // cornerstoneTools.setToolPassive(toolName, {mouseButtonMask: 1})//新增后可编辑,不可连续新增
            cornerstoneTools.setToolActive('Rectangle', {mouseButtonMask: 1}); //可连续新增
          })
        }

      },
      measurementRemoved(evt){
        console.log('measurementRemoved', evt)
        const {measurementData: {handles:{start,end}}, toolName, element} = evt.detail;
        if(toolName === 'Rectangle'){

        }
      },
      updateReferLine(target, reference){
        const targetImagePlane = target._imagePlane
        const referenceImagePlane = reference._imagePlane
        if(!targetImagePlane || !referenceImagePlane) return
        const targetOri = targetImagePlane.view ? targetImagePlane.view : 'axial'
        const referOri = referenceImagePlane.view ? referenceImagePlane.view : 'axial'
        
        if(!targetImagePlane) {
          return false
        }
        const image = {x: 0, y: 0}//模拟任意点
        const c_p_t_i = projectPatientPointToImagePlane(imagePointToPatientPoint(image,referenceImagePlane),targetImagePlane);
        const c_x_y=  cornerstone.pixelToCanvas(target.element,c_p_t_i)
        if(targetOri === 'sagittal' && referOri === 'axial'){
          target.styles.top = this.getMprPosPercent(c_x_y.y, target.$el.clientHeight)
        }else if(targetOri === 'coronal' && referOri === 'axial'){
          target.styles.top = this.getMprPosPercent(c_x_y.y, target.$el.clientHeight)
        }else if(targetOri === 'axial' && referOri === 'sagittal'){
          target.styles.left = this.getMprPosPercent(c_x_y.x, target.$el.clientWidth)
        }else if(targetOri === 'coronal' && referOri === 'sagittal'){
          target.styles.left = this.getMprPosPercent(c_x_y.x, target.$el.clientWidth)
        }else if(targetOri === 'axial' && referOri === 'coronal'){
          target.styles.top = this.getMprPosPercent(c_x_y.y, target.$el.clientHeight)
        }else if (targetOri === 'sagittal' && referOri === 'coronal'){
          target.styles.left = this.getMprPosPercent(c_x_y.x, target.$el.clientWidth)
        }
      },
      drawReferImageLine(evt) {
        let imageId = ''
        if (typeof evt === "string") {
          imageId = evt
        } else {
          imageId = evt.detail.image.imageId
        }
        const { sagittalBoxRef: c_, coronalBoxRef: s_ } = this.mprViewer.$refs // 冠状cell组件/矢状cell组件
        const targetImagePlane = c_._imagePlane
        const referenceImagePlane = cornerstone.metaData.get(
          'imagePlaneModule',
          imageId
        )
        if(!targetImagePlane) {
          return false
        }
        const point = (function(){
          let points = planePlaneIntersection(
            targetImagePlane,
            referenceImagePlane
          );
          if (!points) {
            return;
          }
          return  {
            start: projectPatientPointToImagePlane(_get(points,'start'), targetImagePlane),
            end: projectPatientPointToImagePlane(_get(points,"end"), targetImagePlane),
          };
        })()
        if (point) {
          const { y } = cornerstone.pixelToCanvas(c_.element,point.end)
          c_.styles = { ...c_.styles,top: y+ 'px'}
          s_.styles = { ...s_.styles,top: y+ 'px'}
        }
      },
      //根据方向校验3d坐标，处理超出边界问题
      validatePoint(view, point){
        let axial_x = this.mprViewer.sagittalImageIds.length
        let axial_y = this.mprViewer.coronalImageIds.length
        let axial_z = this.mprViewer.axialImageIds.length
        let {x ,y ,z} = point
        if(view === 'axial'){

        }else if(view === 'sagittal'){
          [axial_x, axial_y, axial_z] = [axial_y,axial_z,axial_x]
        }else if(view === 'coronal'){
          [axial_x, axial_y, axial_z] = [axial_x,axial_z,axial_y]
        }
        x = (x < 0? 0 : x)
        y = (y < 0? 0 : y)
        z = (z < 0? 0 : z)
        x = (x > axial_x?  axial_x : x)
        y = (y > axial_y?  axial_y : y)
        z = (z > axial_z?  axial_z : z)

        return {x, y, z}
      },
      updateImage(){
        cornerstone.updateImage(this.element)
      }
    }
  }
</script>

<style lang="less" scoped>
.mpr-box-fulled {
  position: absolute;
  z-index: 9;
  left: 0;
  top: 0;
}
.mpr-box-normal {
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  position: relative;
  overflow: hidden;
  background-color: #000;
}

.canvas-content {
  width: 100%;
  height: 100%;
}

.iconfont {
  position: absolute;
  top: 4px;
  right: 4px;
  font-size: 16px;
  color: #67C9D5;
  cursor: pointer;
}
</style>
